package com.software.project.controller;

import com.software.project.domain.Result;
import com.software.project.entity.User;
import com.software.project.service.UserService;
import com.software.project.utils.LogUtil;
import com.software.project.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("/test")
    public String test() {
        return request.getRemoteAddr();
    }

    // 查询用户
    @GetMapping("/findUserById")
    public Result<User> findUserById(String id) {
        User user = userService.findUserById(id);
        if (user == null) {
            // 没有查询到用户，非法查询报warn，需检查
            log.warn(LogUtil.error(request.getRemoteAddr(), id));
            return ResultUtil.error("404", "error", null);
        } else {
            // 查询到用户
            log.info(LogUtil.success(request.getRemoteAddr(), id));
            return ResultUtil.success(user);
        }
    }

    // 新增和更新用户
    @PostMapping("/createUser")
    public Result<User> createUser(@RequestBody User user) {
        User create = userService.createUser(user);
        log.info(LogUtil.success(request.getRemoteAddr(), create.toString()));
        return ResultUtil.success(create);
    }

    // 判断是否有账号
    @GetMapping("/checkUserName")
    public Result<User> checkUserName(String userName) {
        User user = userService.checkUserName(userName);
        if (user == null) {
            // 没有账号，需要注册
            log.info(LogUtil.error(request.getRemoteAddr(), userName));
            return ResultUtil.error("404", "error", null);
        } else {
            // 有账号
            log.info(LogUtil.success(request.getRemoteAddr(), userName));
            return ResultUtil.success(user);
        }
    }

    // 判断账号密码是否正确
    @GetMapping("/checkPassword")
    public Result<User> checkPassword(String userName, String password) {
        User user = userService.checkPassword(userName, password);
        if (user == null) {
            // 用户为注册或者密码错误
            log.info(LogUtil.error(request.getRemoteAddr(), userName + " " + password));
            return ResultUtil.error("404", "error", null);
        } else {
            // 账号密码正确
            log.info(LogUtil.success(request.getRemoteAddr(), userName + " " + password));
            return ResultUtil.success(user);
        }
    }
}
